<?php
/*
 * @Descripttion: 
 * @version: 
 * @Author: siebe
 * @Date: 2022-02-15 21:46:45
 * @LastEditors: siebe
 * @LastEditTime: 2022-02-21 03:12:02
 */
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\SystemConfig;
use app\admin\model\SystemMenu;
use app\admin\model\SystemUser;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class Base
{
    public $userInfo = [];
    public $authority = [];
    public $config = [];
    public function __construct()
    {
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            header('location:/admin/login/index');
            exit();
        }
        $user = SystemUser::getUserInfoByID($admin_id);
        if(!$user){
            Session::delete('admin_id');
            header('location:/admin/login/index');
            exit();
        }
        if($user->status != 1){
            Session::delete('admin_id');
            $this->error('管理员账号已被禁用');
        }

        $userInfo = $user->toArray();
        $this->authority = json_decode($userInfo['group']['authority']);
        unset($userInfo['group']);
        $this->userInfo = $userInfo;

        //通过url检查用户权限
        $url = Request::pathinfo();
        $menu = SystemMenu::checkUserPermission($url);
        if(!$menu){
            $this->error("您访问的页面不存在");
        }
        // 通过用户组检查权限
        if(!in_array($menu->id,$this->authority)){
            $this->error("您的部门没有权限");
        }

        $config = SystemConfig::getBaseConfig();
        $this->config = $config;
        View::assign([
            'user' => $this->userInfo,
            'config' => $this->config
        ]);
    }
    public function error($msg){
        $arr = [
            'code' => 0,
            'msg' => $msg
        ];
        $response = view(Config::get('app.exception_error_tmpl'),$arr);
        throw new HttpResponseException($response);
    }
}
